<template>
  <div class="order-detail-view">
    <div class="page-header">
      <div class="header-left">
        <el-button :icon="ArrowLeft" @click="goBack">返回</el-button>
        <div class="header-info">
          <h1>订单详情</h1>
          <p v-if="orderDetail">订单号：{{ orderDetail.order_number }}</p>
        </div>
      </div>
      <div class="header-actions" v-if="orderDetail">
        <el-tag :type="getStatusType(orderDetail.status)" size="large">
          {{ getStatusText(orderDetail.status) }}
        </el-tag>
      </div>
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="8" animated />
    </div>

    <div v-else-if="orderDetail" class="order-content">
      <!-- 订单基本信息 -->
      <el-card class="info-card" shadow="hover">
        <template #header>
          <span class="card-title">订单信息</span>
        </template>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">订单号：</span>
              <span class="value">{{ orderDetail.order_number }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">订单状态：</span>
              <el-tag :type="getStatusType(orderDetail.status)">
                {{ getStatusText(orderDetail.status) }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">下单时间：</span>
              <span class="value">{{ formatDate(orderDetail.created_at) }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 16px;">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">支付时间：</span>
              <span class="value">{{ orderDetail.payment_time ? formatDate(orderDetail.payment_time) : '未支付' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">支付方式：</span>
              <span class="value">{{ orderDetail.payment_method || '未支付' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">交易单号：</span>
              <span class="value">{{ orderDetail.transaction_id || '-' }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 用户信息 -->
      <el-card class="info-card" shadow="hover">
        <template #header>
          <span class="card-title">用户信息</span>
        </template>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">用户昵称：</span>
              <span class="value">{{ orderDetail.user_nickname || '未知用户' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">联系人：</span>
              <span class="value">{{ orderDetail.contact_info?.name || '-' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">联系电话：</span>
              <span class="value">{{ orderDetail.contact_info?.phone || '-' }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 商品信息 -->
      <el-card class="info-card" shadow="hover">
        <template #header>
          <span class="card-title">商品信息</span>
        </template>
        <el-table :data="orderDetail.items" style="width: 100%">
          <el-table-column label="商品信息" min-width="300">
            <template #default="{ row }">
              <div class="product-info">
                <el-image
                  :src="row.product_image_url"
                  class="product-image"
                  fit="cover"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div class="product-details">
                  <div class="product-name">{{ row.product_name }}</div>
                  <div class="product-current" v-if="row.current_product_name">
                    当前商品名：{{ row.current_product_name }}
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="单价" width="120" align="center">
            <template #default="{ row }">
              ¥{{ row.price?.toFixed(2) || '0.00' }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100" align="center" />
          <el-table-column label="小计" width="120" align="center">
            <template #default="{ row }">
              ¥{{ ((row.price || 0) * (row.quantity || 0)).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 费用明细 -->
      <el-card class="info-card" shadow="hover">
        <template #header>
          <span class="card-title">费用明细</span>
        </template>
        <div class="price-summary">
          <div class="price-item">
            <span class="label">商品总价：</span>
            <span class="value">¥{{ orderDetail.total_amount?.toFixed(2) || '0.00' }}</span>
          </div>
          <div class="price-item">
            <span class="label">运费：</span>
            <span class="value">¥{{ orderDetail.shipping_fee?.toFixed(2) || '0.00' }}</span>
          </div>
          <div class="price-item total">
            <span class="label">实付金额：</span>
            <span class="value">¥{{ orderDetail.payment_amount?.toFixed(2) || '0.00' }}</span>
          </div>
        </div>
      </el-card>

      <!-- 订单备注 -->
      <el-card v-if="orderDetail.customer_notes" class="info-card" shadow="hover">
        <template #header>
          <span class="card-title">订单备注</span>
        </template>
        <div class="notes-content">
          {{ orderDetail.customer_notes }}
        </div>
      </el-card>

      <!-- 操作按钮 -->
      <div class="action-buttons" v-if="orderDetail.status === 'processing'">
        <el-button
          type="primary"
          size="large"
          @click="handleShipOrder"
        >
          标记发货
        </el-button>
      </div>
    </div>

    <div v-else class="error-container">
      <el-empty description="订单不存在或已被删除" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Picture } from '@element-plus/icons-vue'
import { request } from '@/utils/request'

// 路由
const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const orderDetail = ref<any>(null)

// 获取订单详情
const fetchOrderDetail = async () => {
  try {
    loading.value = true
    const orderId = route.params.id
    const response = await request.get(`/orders/${orderId}`)
    orderDetail.value = response.data
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 标记发货
const handleShipOrder = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要将订单 ${orderDetail.value.order_number} 标记为已发货吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await request.put(`/orders/${orderDetail.value.id}/status`, { status: 'shipped' })
    ElMessage.success('订单状态更新成功')
    fetchOrderDetail() // 重新获取订单详情
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新订单状态失败:', error)
      ElMessage.error('更新订单状态失败')
    }
  }
}

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'pending_payment': 'warning',
    'processing': 'primary',
    'shipped': 'info',
    'completed': 'success',
    'cancelled': 'danger',
    'refunded': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'pending_payment': '待支付',
    'processing': '待发货',
    'shipped': '待收货',
    'completed': '已完成',
    'cancelled': '已取消',
    'refunded': '已退款'
  }
  return statusMap[status] || '未知状态'
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchOrderDetail()
})
</script>

<style scoped>
.order-detail-view {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-info h1 {
  margin: 0 0 4px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-info p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.loading-container,
.error-container {
  padding: 40px 0;
}

.info-card {
  margin-bottom: 20px;
}

.card-title {
  font-weight: 600;
  color: #303133;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item .label {
  color: #606266;
  font-size: 14px;
  min-width: 80px;
}

.info-item .value {
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  flex-shrink: 0;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.product-details {
  flex: 1;
}

.product-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.product-current {
  font-size: 12px;
  color: #909399;
}

.price-summary {
  max-width: 400px;
  margin-left: auto;
}

.price-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.price-item:last-child {
  border-bottom: none;
}

.price-item.total {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  border-top: 2px solid #e4e7ed;
  margin-top: 8px;
  padding-top: 16px;
}

.price-item .label {
  color: #606266;
}

.price-item .value {
  color: #303133;
  font-weight: 500;
}

.price-item.total .value {
  color: #f56c6c;
  font-size: 18px;
}

.notes-content {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  color: #303133;
  line-height: 1.6;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 30px;
  padding: 20px 0;
}
</style>
